package com.dayatang.product.webapp.interceptor;

import java.util.Date;

import javax.inject.Inject;

import com.dayatang.product.application.ProductApplication;
import com.dayatang.product.domain.PersonUser;
import com.dayatang.product.domain.SystemException;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 文件名:ExceptionInterceptor.java
 * 描述:异常拦截器
 * 创建时间:2012-7-2 上午11:54:39
 * 创建者:mluo
 * 版本号:v2.0
 */
public class ExceptionInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -6832406112699188766L;
	private static final String EXECPTION = "execption";

	@Inject
	private ProductApplication productApplication;
	
	public String intercept(ActionInvocation invocation) throws Exception {
		String result = null;
		try {
			result = invocation.invoke();
		} catch (Exception e) {
			PersonUser personUser = (PersonUser) invocation.getInvocationContext().getSession().get("LOGINUSER");
			SystemException systemException = new SystemException();
			systemException.setName(personUser.getPerson().getName());
			systemException.setActionName(invocation.getAction().toString());
			systemException.setExceptionText(getExceptionString(e));
			systemException.setExceptionDate(new Date());
			productApplication.saveEntity(systemException);
			result = EXECPTION;
		}
		return result;
	}
	
	private String getExceptionString(Exception e) {
		StringBuilder builder = new StringBuilder();
		int i = 0;
		for (StackTraceElement element : e.getStackTrace()) {
			if (i < 100) {
				builder.append(element.toString()).append("<br>");
				i++;
			}
		}
		return builder.toString();
	}

	public void setProductApplication(ProductApplication productApplication) {
		this.productApplication = productApplication;
	}

}


